<template>
    <el-card>
        <el-row :gutter="20">
            <el-col :span="6">
                <el-input v-model="SearchParams.orderNo" placeholder="请输入订单号"></el-input>
            </el-col>
            <el-col :span="6">
                <el-select v-model="SearchParams.status">
                    <el-option label="全部" :value="0"></el-option>
                    <el-option label="进行中" :value="1"></el-option>
                    <el-option label="已完成" :value="2"></el-option>
                    <el-option label="异常" :value="3"></el-option>
                </el-select>
            </el-col>
            <el-col :span="6">
                <el-input v-model="SearchParams.no" placeholder="设备编号"></el-input>
            </el-col>
            <el-col :span="6">
                <el-button type="primary" @click="loadData">查询</el-button>
                <el-button @click="handleReset">重置</el-button>
            </el-col>
            <el-col class="mt" :span="6">
                <el-input v-model="SearchParams.name" placeholder="请输入站点名称"></el-input>
            </el-col>
            <el-col class="mt" :span="6">
                <el-date-picker v-model="date" is-range type="daterange" range-separator="/" start-placeholder="开始时间"
                    end-placeholder="结束时间" @change="handleChange" value-format="YYYY-MM-DD" />
            </el-col>
        </el-row>
    </el-card>
    <el-card class="mt">
        <template #default="scope">
            <el-button type="danger" :disabled="!selectionList.length" @click="handleBatchDelete">批量删除</el-button>
            <el-button type="primary" :disabled="!selectionList.length" @click="exportToExcel">
                <el-icon style="margin-right: 10px;">
                    <Download />
                </el-icon>
                导出订单数据到Excel
            </el-button>
        </template>
    </el-card>
    <el-card class="mt">
        <el-table :data="dataList" style="width: 100%;" v-loading="loading" @selection-change="handleSelection">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column label="序号" type="index" width="80px"></el-table-column>
            <el-table-column label="订单号" prop="orderNo"></el-table-column>
            <el-table-column label="设备编号" prop="equipmentNo"></el-table-column>
            <el-table-column label="订单日期" prop="date"></el-table-column>
            <el-table-column label="开始时间" prop="startTime"></el-table-column>
            <el-table-column label="结束时间" prop="endTime"></el-table-column>
            <el-table-column label="金额" prop="money"></el-table-column>
            <el-table-column label="支付方式" prop="pay"></el-table-column>
            <el-table-column label="订单状态" prop="status">
                <template #default="scope">
                    <el-tag
                        :type="scope.row.status === 2 ? 'primary' : (scope.row.status === 3 ? 'success' : 'danger')">
                        {{ scope.row.status === 2 ? '进行中' : (scope.row.status === 3 ? '已完成' : '异常') }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template #default="scope">
                    <el-button type="primary" @click="handleDetail(scope.row.orderNo)">详情</el-button>
                    <el-button type="danger" @click="handleDelete(scope.row.orderNo)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination class="mt mb fr" v-model:current-page="pageInfo.page" v-model:page-size="pageInfo.pageSize"
            :page-sizes="[10, 20, 30, 40]" background layout="total, sizes, prev, pager, next, jumper" :total="totals"
            @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </el-card>
</template>

<script setup lang="ts">
// 主要功能是通过selection-change
import { ref, watch } from 'vue'
import { useHttp } from '@/hook/useHttps'
import { batchDeleteAPI } from '@/api/operation'
import { ElMessage } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
import { useTabsStore } from '@/store/tabs'
import * as XLSX from 'xlsx'
import {saveAs} from 'file-saver'
// 双向绑定数据类型
interface SearchType {
    orderNo: string,
    status: number,
    no: string,
    name: string,
    startDate: string,
    endDate: string
}
// 前端的双向绑定数据，日期需要借助@change事件，然后获取到当前日期进行赋值
const SearchParams = ref<SearchType>({
    orderNo: '',
    status: 0,
    no: '',
    name: '',
    startDate: '',
    endDate: ''
})
// 后端返回的数据的类型
interface SelectionListType {
    orderNo: string,
    equipmentNo: string,
    date: string,
    startTime: string
    endTime: string,
    money: string,
    pay: string,
    status: number
}
// 日期的双向绑定
const date = ref()

const handleChange = (val: any) => {
    SearchParams.value.startDate = val[0]
    SearchParams.value.endDate = val[1]
}

const { dataList, totals, loading, pageInfo, loadData, handleSizeChange, handleCurrentChange, resetPagination } = useHttp<SelectionListType>("/orderList", SearchParams.value)
// 重置
const handleReset = () => {
    SearchParams.value = {
        orderNo: '',
        status: 0,
        no: '',
        name: '',
        startDate: '',
        endDate: ''
    }
    resetPagination()
}
//是否选中了复选框 @selection-change
const selectionList = ref<SelectionListType[]>([])
const handleSelection = (selection: SelectionListType[]) => {
    selectionList.value = selection
}

// 批量删除,通过选中的select-change方法里面存的selecttionList取出里面的orderNo
const handleBatchDelete = async () => {
    try {
        // 通过map把id取出来
        const res = await batchDeleteAPI(selectionList.value.map((item: SelectionListType) => item.orderNo))
        if (res.code === 200) {
            ElMessage({
                message: '批量删除成功',
                type: 'success',
                plain: true,
            })
        }
        loadData()
    } catch (error) {
        console.log(error)
    }
}
// 单个删除
const handleDelete = async (orderNo: string) => {
    try {
        const res = await batchDeleteAPI(orderNo)
        if (res.code === 200) {
            ElMessage({
                message: '删除成功',
                type: 'success',
                plain: true,
            })
        }
        loadData()
    } catch (error) {
        console.log(error)
    }
}



// 订单详情
const router = useRouter()
const tabStore = useTabsStore()
const { addTab, setActiveTab, removeTabs } = tabStore
const handleDetail = async (orderNo: string) => {
    // 添加到tab里面
    addTab('订单详情', 'Share', "/operations/detail")
    // 跳转到页面之后设置高亮
    setActiveTab('订单详情', "/operations/detail")
    router.push("/operations/detail?orderNo=" + orderNo)
}
const route = useRoute()
watch(() => route.name, (to, from) => {
    if (to === 'orders' && from != 'detail') {
        loadData()
        return
    }
    if (from == 'detail') {
        removeTabs('订单详情')
    }
})
const exportToExcel = ()=>{
    const ws = XLSX.utils.json_to_sheet(selectionList.value)
    const wb = XLSX.utils.book_new()
    XLSX.utils.book_append_sheet(wb,ws,'Sheet1')
    const wbout = XLSX.write(wb,{bookType:'xlsx',type:'array'})
    const blob = new Blob([wbout],{type:'application/octet-stream'})
    saveAs(blob,'导出的数据.xlsx')
}
</script>


<style scoped lang="less">
::v-deep .el-date-editor {
    background-color: white;
}
</style>